package com.link.play.fit.ai.ui.main.fragment

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.content.res.ColorStateList
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.graphics.drawable.LayerDrawable
import android.os.Bundle
import android.view.View
import androidx.core.app.ActivityOptionsCompat
import androidx.core.util.Pair
import androidx.lifecycle.lifecycleScope
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.data.BarData
import com.github.mikephil.charting.data.BarDataSet
import com.github.mikephil.charting.data.BarEntry
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.formatter.ValueFormatter
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayout.OnTabSelectedListener
import com.google.firebase.firestore.Filter
import com.google.firebase.firestore.ListenerRegistration
import com.link.play.fit.ai.GlobalConfig
import com.link.play.fit.ai.R
import com.link.play.fit.ai.base.BaseActivity
import com.link.play.fit.ai.base.BaseFragment
import com.link.play.fit.ai.base.goToAc
import com.link.play.fit.ai.base.goToAcForResult
import com.link.play.fit.ai.base.viewBind
import com.link.play.fit.ai.bean.LogWeightBean
import com.link.play.fit.ai.bean.RecentlyEatenData
import com.link.play.fit.ai.bean.UserGuide
import com.link.play.fit.ai.databinding.FgAnalyticsBinding
import com.link.play.fit.ai.ext.d
import com.link.play.fit.ai.ext.setThrottleListener
import com.link.play.fit.ai.store.CloudStore
import com.link.play.fit.ai.store.CloudStore.DOC_LOG_WEIGHT
import com.link.play.fit.ai.store.CloudStore.DOC_RECENTLY_LIST_DATA
import com.link.play.fit.ai.store.CloudStore.DOC_USER_GUIDE
import com.link.play.fit.ai.ui.bmi.BmiAc
import com.link.play.fit.ai.ui.dialog.CongratulationDialog
import com.link.play.fit.ai.ui.main.MainAc
import com.link.play.fit.ai.ui.main.MainViewModel
import com.link.play.fit.ai.ui.main.setting.SettingAc
import com.link.play.fit.ai.ui.scanFood.FoodDetailAc
import com.link.play.fit.ai.ui.setting.SetUserInfoAc
import com.link.play.fit.ai.ui.setting.SetWeightAc
import com.link.play.fit.ai.utils.BmiUtils
import com.link.play.fit.ai.utils.DateEx.getDayOfMonth
import com.link.play.fit.ai.utils.DateEx.getTimestampForDaysAgo
import com.link.play.fit.ai.utils.DateEx.getTimestampForMonthsAgo
import com.link.play.fit.ai.utils.DateEx.getTimestampForYearsAgo
import com.link.play.fit.ai.utils.LogX
import com.link.play.fit.ai.utils.RoundBarChartRender
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.math.BigDecimal
import java.math.RoundingMode
import java.text.SimpleDateFormat
import java.time.DayOfWeek
import java.time.Instant
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.Date
import java.util.Locale

/**
 *Create by SleepDog on 2025-03-24
 * 分析
 */
class AnalyticsFg : BaseFragment<FgAnalyticsBinding>(FgAnalyticsBinding::inflate) {
    private val viewModel: MainViewModel by lazy { (requireActivity() as MainAc).viewModel }

    /**
     * 从星期天开始算起的一周
     */
    private val weekArray = arrayOf("S", "M", "T", "W", "T", "F", "S")

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        initListener()
    }

    /**
     * 用来保存firestore的数据监听，在不需要的时候需要去除掉，这里固定写死了3个
     */
    private val observerList = ArrayList<ListenerRegistration>(3)

    /**
     * 用来防止多次请求刷新，因为有些数据改变的监听是有重合的
     */
    private var isUpdateData = false

    private val dateFormatter by lazy(LazyThreadSafetyMode.NONE) {
        DateTimeFormatter.ofPattern("dd MMM", Locale.getDefault())
    }

    private fun initListener() {
        viewBind {
            tvLogWeight.setThrottleListener {
                lifecycleScope.launch {
                    val before = CloudStore.get<UserGuide>(DOC_USER_GUIDE) ?: UserGuide()
                    val result = (requireActivity() as MainAc).goToAcForResult(SetWeightAc::class.java)
                    val after = CloudStore.get<UserGuide>(DOC_USER_GUIDE) ?: UserGuide()
                    if (result.resultCode == Activity.RESULT_OK) {

                        if (after.imperialMetric) {
                            val change = after.weightKg - before.weightKg
                            if (before.goal == 0 && change <= 0) {
                                return@launch
                            }
                            if (before.goal == 2 && change >= 0) {
                                return@launch
                            }
                            CongratulationDialog(requireActivity() as MainAc).showDialog(true, change, after.weightKg)
                        } else {
                            val change = after.weightLbs - before.weightLbs
                            if (before.goal == 0 && change <= 0) {
                                return@launch
                            }
                            if (before.goal == 2 && change >= 0) {
                                return@launch
                            }
                            CongratulationDialog(requireActivity() as MainAc).showDialog(false, change, after.weightLbs)
                        }

                    }

                }
            }
            tvUpdate.setThrottleListener {
                goToAc(SetUserInfoAc::class.java) {
                    putExtra(SetUserInfoAc.Type, SetUserInfoAc.goalWeight)
                }
            }
            ivTips.setThrottleListener {
                goToAc(
                    BmiAc::class.java,
                    ActivityOptionsCompat.makeSceneTransitionAnimation(
                        requireActivity(),
                        Pair(
                            binding.sbBmi, getString(R.string.bmi)
                        ), Pair(
                            binding.tvBmi, getString(R.string.your_bmi)
                        ), Pair(
                            binding.tvWeightIs, getString(R.string.your_weight_is)
                        ), Pair(
                            binding.tvBmiLabel, getString(R.string.bmi_disclaimer)
                        )
                    ).toBundle()
                )
            }

            tlWeight.addOnTabSelectedListener(object : OnTabSelectedListener {
                override fun onTabSelected(tab: TabLayout.Tab) {
                    refreshWeightBarData(tab.position)
                }

                override fun onTabUnselected(tab: TabLayout.Tab?) {

                }

                override fun onTabReselected(tab: TabLayout.Tab?) {
                }

            })
            tlNutrition.addOnTabSelectedListener(object : OnTabSelectedListener {
                override fun onTabSelected(tab: TabLayout.Tab) {
                    refreshNutritionBarData(tab.position)
                }

                override fun onTabUnselected(tab: TabLayout.Tab?) {

                }

                override fun onTabReselected(tab: TabLayout.Tab?) {
                }

            })
            settingImg.setOnClickListener{
                goToAc(SettingAc::class.java){
                    putExtra("data", viewModel.getCalendarData())
                }
//                lifecycleScope.launch {
//                    val result = requireActivity().goToAcForResult(
//                        SettingAc::class.java
//                    ) {
//                        putExtra("data", viewModel.getCalendarData())
//                    }
//                    val value = result.data?.getStringExtra("result")
//                    "value $value result ${result.data}".d()
//
//                    value?.let {
//                        viewModel.onclickTapScan(it)
//                    }
//                }
            }
        }
    }

    private fun refreshWeightBarData(pos: Int) {
        lifecycleScope.launch(Dispatchers.Default) {
            val currentTime = System.currentTimeMillis()
            val filterTime = when (pos) {
                1 -> getTimestampForMonthsAgo(6)
                2 -> getTimestampForYearsAgo(1)
                3 -> currentTime
                else -> getTimestampForDaysAgo(90)
            }
            val dataList = CloudStore.getList<LogWeightBean>(
                DOC_LOG_WEIGHT,
                DOC_LOG_WEIGHT,
                if (currentTime > filterTime) Filter.and(
                    Filter.greaterThanOrEqualTo("createTime", filterTime),
                    Filter.lessThanOrEqualTo("createTime", currentTime)
                ) else Filter.lessThanOrEqualTo("createTime", currentTime)
            )
            val entries =
                if (dataList?.isNotEmpty() == true) {
                    val list = ArrayList<Entry>(dataList.size)
                    dataList.forEachIndexed { index, it ->
                        list.add(
                            Entry(
                                index.toFloat(),
                                (if (GlobalConfig.imperialMetric) it.weightKg else it.weightLbs).toFloat(),
                                it.createTime
                            )
                        )
                    }
                    list
                } else emptyList()
            withContext(Dispatchers.Main) {
                initWeightChart(entries)
            }
        }
    }

    private fun refreshNutritionBarData(pos: Int) {
        lifecycleScope.launch(Dispatchers.Default) {
            //先获取根据前pos周中的一周的时间戳
            val timeList = getWeekDaysTimestamp(pos)
            val format = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
            //筛选类型为食物类型
            val filter1 = Filter.or(
                Filter.equalTo("type", 2),
                Filter.equalTo("type", 3),
                Filter.equalTo("type", 4)
            )
            val filter = Filter.and(Filter.equalTo("showType", 1), filter1)
            //总卡路里
            var totalCal = 0
            val entries = ArrayList<BarEntry>(timeList.size)
            //用于计算平均每天卡路里，这里有数据才算一天
            var realSize = 0
            //用于计算本周总成分量
            var totalNew = 0
            timeList.forEachIndexed { index, it ->
                var carbs = 0
                var protein = 0
                var fats = 0
                val list = CloudStore.getList<RecentlyEatenData>(
                    DOC_RECENTLY_LIST_DATA,
                    format.format(Date(it)), filter
                )
                if (!list.isNullOrEmpty()) realSize++
                list?.forEach { bean ->
                    totalCal += bean.caloriesDaily
                    carbs += bean.carbsDaily
                    protein += bean.proteinDaily
                    fats += bean.fatsDaily
                    totalNew += bean.carbsDaily
                    totalNew += bean.proteinDaily
                    totalNew += bean.fatsDaily
                    //LogX.e(TAG, bean.toString())
                }
                entries.add(
                    BarEntry(
                        index.toFloat(),
                        floatArrayOf(fats.toFloat(), carbs.toFloat(), protein.toFloat())
                    )
                )
            }
            //计算平均每天的卡路里
            val dailyAvg =
                if (realSize > 0) BigDecimal((totalCal.toFloat() / realSize).toString()).setScale(
                    1,
                    RoundingMode.HALF_UP
                ).toString() else "0"
            withContext(Dispatchers.Main) {
                binding.tvTotal.text = totalCal.toString()
                binding.tvDaily.text = dailyAvg
            }
            initNutritionChart(entries)
            //只有第一个tab选项才设置百分比吧，免得刷新太频繁
            if (pos == 0) refreshNutritionPercent(totalNew, format, filter)
        }
    }

    /**
     * 刷新本周与上周数据的百分比
     * @param totalNew 本周的所有成分量
     * @param format 时间格式
     * @param filter 筛选条件
     */
    private fun refreshNutritionPercent(totalNew: Int, format: SimpleDateFormat, filter: Filter) {
        lifecycleScope.launch(Dispatchers.Default) {
            //先获取根据前一周中的一周的时间戳
            val timeList = getWeekDaysTimestamp(1)
            var totalLast = 0
            timeList.forEach {
                val list = CloudStore.getList<RecentlyEatenData>(
                    DOC_RECENTLY_LIST_DATA,
                    format.format(Date(it)), filter
                )
                list?.forEach { bean ->
                    totalLast += bean.carbsDaily
                    totalLast += bean.proteinDaily
                    totalLast += bean.fatsDaily
                }
            }
            if (totalLast <= 0 && totalNew <= 0) return@launch
            val arrow =
                if (totalNew > totalLast) R.drawable.ic_arrow else if (totalNew < totalLast) R.drawable.ic_arrow_down else 0
            val percent =
                "${
                    if (totalLast > 0) BigDecimal((totalNew.toFloat() / totalLast).toString()).setScale(
                        1, RoundingMode.HALF_UP
                    ).multiply(BigDecimal(100)) else 100
                }%"
            withContext(Dispatchers.Main) {
                binding.tvNutritionPercent.text = percent
                binding.tvNutritionPercent.setCompoundDrawablesWithIntrinsicBounds(
                    arrow, 0, 0, 0
                )
                binding.tvNutritionPercent.setTextColor(
                    if (totalNew > totalLast) Color.parseColor("#FF99DE87") else if (totalNew < totalLast) requireContext().getColor(
                        R.color.color_FF3B2F
                    ) else requireContext().getColor(
                        R.color.color_1d1a23
                    )
                )
            }
        }
    }

    /**
     * 根据当日计算n周前的一周的日期
     * @param n n周前
     * @return 一周的日期时间戳
     */
    private fun getWeekDaysTimestamp(n: Int): List<Long> {
        // 获取当前日期
        val today = LocalDate.now()

        // 计算 n 周前的日期
        val nWeeksAgo = today.minusWeeks((n + 1).toLong())

        // 找到 n 周前的那一周的周日
        val startOfWeek = nWeeksAgo.with(DayOfWeek.SUNDAY)

        // 生成一周内的所有日期（周日到周六）
        val dates = ArrayList<LocalDate>(7)
        for (i in 0 until 7) {
            dates.add(startOfWeek.plusDays(i.toLong()))
        }

        // 将日期转换为时间戳（以当天的开始时间为基准）
        return dates.map { date ->
            LocalDateTime.of(date, date.atStartOfDay().toLocalTime())
                .atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    private fun initView() {
        viewBind {
            //--------BMI相关--------------
            // 创建渐变色的Drawable
            val gradientDrawable = GradientDrawable(
                GradientDrawable.Orientation.LEFT_RIGHT,
                intArrayOf(
                    resources.getColor(R.color.color_007BFF, null),
                    resources.getColor(R.color.color_34C85A, null),
                    resources.getColor(R.color.color_FFD60A, null),
                    resources.getColor(R.color.color_FF3B2F, null)
                )
            )
            gradientDrawable.gradientType = GradientDrawable.LINEAR_GRADIENT
            gradientDrawable.shape = GradientDrawable.RECTANGLE
            gradientDrawable.cornerRadius = 9f // 设置圆角

            // 创建LayerDrawable，用于设置进度条的背景
            val layerDrawable = LayerDrawable(arrayOf(gradientDrawable))
            sbBmi.progressDrawable = layerDrawable
            sbBmi.setOnTouchListener { _, _ -> true }
            //--------BMI相关结束--------------

            tlWeight.addTab(tlWeight.newTab().setText(getString(R.string.days_90)))
            tlWeight.addTab(tlWeight.newTab().setText(getString(R.string.months_6)))
            tlWeight.addTab(tlWeight.newTab().setText(getString(R.string.year_1)))
            tlWeight.addTab(tlWeight.newTab().setText(getString(R.string.all_time)))

            tlNutrition.addTab(tlNutrition.newTab().setText(getString(R.string.this_week)))
            tlNutrition.addTab(tlNutrition.newTab().setText(getString(R.string.last_week)))
            tlNutrition.addTab(tlNutrition.newTab().setText(getString(R.string.wks_ago_2)))
            tlNutrition.addTab(tlNutrition.newTab().setText(getString(R.string.wks_ago_3)))

            initWeightChart(isRefresh = false)

            initNutritionChart(isRefresh = false)
        }
    }

    private inline fun updateWeightGoal(isMetric: Boolean, crossinline updateDone: (() -> Unit)) {
        isUpdateData = true
        lifecycleScope.launch(Dispatchers.Default) {
            val data = CloudStore.get<UserGuide>(DOC_USER_GUIDE)
            val goalWeight: String = if (isMetric) {
                "${data?.goalWeightKg ?: ""} kg"
            } else {
                "${data?.goalWeightLbs ?: ""} lbs"
            }
            val dataCurrent = CloudStore.getListItem<LogWeightBean>(
                DOC_LOG_WEIGHT,
                DOC_LOG_WEIGHT,
                Filter.lessThanOrEqualTo("createTime", System.currentTimeMillis())
            )
            val currentWeight: String = if (isMetric) {
                "${dataCurrent?.weightKg} kg"
            } else {
                "${dataCurrent?.weightLbs} lbs"
            }
            updateBmi(data?.heightCm, dataCurrent?.weightKg)
            updateGoalPercent(data?.goalWeightKg, dataCurrent?.weightKg, data?.goal)
            withContext(Dispatchers.Main) {
                binding.tvWeightGoal.text = goalWeight
                binding.tvCurrentWeight.text = currentWeight
                isUpdateData = false
                updateDone()
            }
        }
    }

    override fun lazyInit() {
        lifecycleScope.launch {
            //公英制状态变化
            GlobalConfig.imperialMetricFlow.collectLatest {
                updateWeightGoal(it) {}
                refreshWeightBarData(binding.tlWeight.selectedTabPosition)
            }
        }
        //监听当天体重记录变化
        observerList.add(CloudStore.observeList(
            DOC_LOG_WEIGHT, DOC_LOG_WEIGHT
        ) { value, error ->
            if (error != null || isUpdateData) {
                return@observeList
            }
            lifecycleScope.launch(Dispatchers.Default) {
                val data =
                    if (value != null && !value.isEmpty) value.toObjects(LogWeightBean::class.java)
                        .last() else null
                val currentWeight: String = if (GlobalConfig.imperialMetric) {
                    "${data?.weightKg} kg"
                } else {
                    "${data?.weightLbs} lbs"
                }
                updateBmi(cacheWeight = data?.weightKg)
                updateGoalPercent(cacheWeight = data?.weightKg)
                refreshWeightBarData(binding.tlWeight.selectedTabPosition)
                withContext(Dispatchers.Main) {
                    viewBind {
                        tvCurrentWeight.text = currentWeight
                    }
                }
            }
        })
        //监听体重目标变化(监听颗粒度有点大浪费流量，将就吧，理论上可以针对某个参数变化监听)
        observerList.add(CloudStore.observe(
            DOC_USER_GUIDE
        ) { value, error ->
            if (error != null || isUpdateData) {
                return@observe
            }
            lifecycleScope.launch(Dispatchers.Default) {
                val data =
                    if (value?.exists() == true) value.toObject(UserGuide::class.java) else null
                val goalWeight: String = if (data?.imperialMetric == true) {
                    "${data.goalWeightKg} kg"
                } else {
                    "${data?.goalWeightLbs} lbs"
                }
                updateGoalPercent(data?.goalWeightKg)
                withContext(Dispatchers.Main) {
                    viewBind {
                        tvWeightGoal.text = goalWeight
                    }
                }
            }
        })

        //监听当天的用餐变化
        observerList.add(CloudStore.observeList(
            DOC_RECENTLY_LIST_DATA, getDayOfMonth()
        ) { _, error ->
            if (error != null) {
                return@observeList
            }
            refreshNutritionBarData(binding.tlNutrition.selectedTabPosition)
        })

    }

    override fun onDestroyView() {
        super.onDestroyView()
        //去除所有的firestore监听
        observerList.forEach { it.remove() }
        observerList.clear()
    }

    private fun updateBmi(cacheHeight: Int? = null, cacheWeight: Int? = null) {
        lifecycleScope.launch(Dispatchers.Default) {
            val height =
                cacheHeight ?: CloudStore.get<UserGuide>(DOC_USER_GUIDE)?.heightCm ?: 0

            val weight = cacheWeight ?: CloudStore.getListItem<LogWeightBean>(
                DOC_LOG_WEIGHT,
                DOC_LOG_WEIGHT,
                getDayOfMonth()
            )?.weightKg ?: 0
            val bmi = BmiUtils.getBmi(weight, height)
            val level = BmiUtils.getLevel(bmi)
            val data = BmiUtils.getData(level)
            withContext(Dispatchers.Main) {
                viewBind {
                    tvBmi.text = bmi.toString()
                    tvBmiLabel.backgroundTintList = ColorStateList.valueOf(data.second)
                    tvBmiLabel.text = data.first
                    sbBmi.progress = level * 2 + 1
                }
            }
        }
    }

    /**
     * 计算并更新达到目标的百分比
     * @param cacheGoalWeight 目标体重，不传的话就回去存储里面获取一下
     * @param cacheWeight 当前体重，不传的话就回去存储里面获取一下
     */
    private fun updateGoalPercent(
        cacheGoalWeight: Int? = null,
        cacheWeight: Int? = null,
        goalType: Int? = null
    ) {
        lifecycleScope.launch(Dispatchers.Default) {
            val goalWeight =
                cacheGoalWeight ?: CloudStore.get<UserGuide>(DOC_USER_GUIDE)?.goalWeightKg ?: 0

            val weight = cacheWeight ?: CloudStore.getListItem<LogWeightBean>(
                DOC_LOG_WEIGHT,
                DOC_LOG_WEIGHT,
                getDayOfMonth()
            )?.weightKg ?: 0
            val percent =
                if (weight != 0 && goalWeight != 0 && goalType != -1) {
                    if (goalType == 0) weight.toFloat() / goalWeight.toFloat() * 100
                    else goalWeight.toFloat() / weight.toFloat() * 100
                } else 0.0f
            withContext(Dispatchers.Main) {
                binding.tvGoalPercent.text = buildString {
                    append(
                        BigDecimal(percent.toDouble()).setScale(1, RoundingMode.HALF_UP).toFloat()
                    )
                    append("%")
                }
            }
        }
    }

    /**
     * 用来生成空的柱状图数据列表
     * @return 空数据列表
     */
    private fun generateEmptyBar(): List<BarEntry> {
        val emptyData = floatArrayOf(0f, 0f, 0f)
        return MutableList(7) {
            BarEntry(it.toFloat(), emptyData)
        }
    }

    private fun initWeightChart(entries: List<Entry> = emptyList(), isRefresh: Boolean = true) {
        LineDataSet(entries, "").also {
            it.setDrawIcons(false)
            it.setDrawValues(true)
            it.mode = LineDataSet.Mode.HORIZONTAL_BEZIER
            it.color = requireContext().getColor(R.color.black)
            it.lineWidth = 1f
            it.circleRadius = 4f
            it.circleHoleRadius = 2f
            it.setCircleColor(it.color)
            it.valueFormatter = object : ValueFormatter() {

                override fun getFormattedValue(value: Float): String {
                    return value.toInt().toString()
                }
            }
            with(binding.chartWeight) {
                runCatching {
                    xAxis.valueFormatter = null
                    data = LineData(it)
                }.onFailure { error ->
                    LogX.e(TAG, "chartWeight:${error}  ${error.message}")
                }

                if (!isRefresh) {
                    isDoubleTapToZoomEnabled = false
                    axisRight.isEnabled = false
                    // axisLeft.setDrawAxisLine(true)
                    axisLeft.textSize = 10f
                    axisLeft.granularity = 0.4f
                    axisLeft.textColor =
                        requireContext().getColor(R.color.color_1d1a23)
                    axisLeft.mAxisRange = 1f
                    axisLeft.valueFormatter = object : ValueFormatter() {

                        override fun getFormattedValue(value: Float): String {

                            return String.format(
                                Locale.getDefault(),
                                "%.1f %s",
                                value,
                                if (GlobalConfig.imperialMetric) "kg" else "lbs"
                            )

                        }
                    }
                    xAxis.setDrawGridLines(false)
                    xAxis.textSize = 10f
                    xAxis.textColor =
                        requireContext().getColor(R.color.color_1d1a23)
                    xAxis.position = XAxis.XAxisPosition.BOTTOM
                    xAxis.granularity = 1f
                    description.isEnabled = false
                    legend.isEnabled = false
                    extraBottomOffset = 18f
                    extraRightOffset = 18f
                    setPinchZoom(true)
                }
                xAxis.valueFormatter = object : ValueFormatter() {

                    override fun getFormattedValue(value: Float): String {
                        if (value < 0 || entries.isEmpty()) return dateFormatter.format(
                            Instant.ofEpochMilli(System.currentTimeMillis())
                                .atZone(ZoneId.systemDefault())
                                .toLocalDateTime()
                        )
                        val index = value.toInt()
                        if (index >= entries.size) {
                            return ""
                        }
                        val time = entries[index].data as Long
                        return dateFormatter.format(
                            Instant.ofEpochMilli(time).atZone(ZoneId.systemDefault())
                                .toLocalDateTime()
                        )
                    }

                }
                //刷新状态的时候就需要重新刷新视图，第一次初始化不用哦
                if (isRefresh) invalidate()
            }

        }
    }


    private fun initNutritionChart(
        entries: List<BarEntry> = generateEmptyBar(),
        isRefresh: Boolean = true
    ) {
        BarDataSet(entries, "").also {
            it.setDrawIcons(false)
            it.setDrawValues(false)
            it.setColors(
                Color.parseColor("#FF4885F3"),
                Color.parseColor("#FFFFC23F"),
                Color.parseColor("#FFFF3C73")
            )
            with(binding.chartNutrition) {
                runCatching {
                    data = BarData(it)
                }.onFailure { error ->
                    LogX.e(TAG, "chartNutrition:${error}  ${error.message}")
                }

                data.barWidth = 0.4f
                if (!isRefresh) {
                    isDoubleTapToZoomEnabled = false
                    //setTouchEnabled(false)
                    axisRight.isEnabled = false
                    axisLeft.setDrawGridLines(false)
                    axisLeft.textSize = 10f
                    axisLeft.granularity = 0.4f
                    axisLeft.textColor =
                        requireContext().getColor(R.color.color_1d1a23)
                    axisLeft.mAxisRange = 1f
                    axisLeft.axisMinimum = 0f
                    axisLeft.valueFormatter = object : ValueFormatter() {

                        override fun getFormattedValue(value: Float): String {
                            return String.format(Locale.getDefault(), "%.1f", value)
                        }
                    }
                    xAxis.setDrawGridLines(false)
                    xAxis.textSize = 10f
                    xAxis.textColor =
                        requireContext().getColor(R.color.color_1d1a23)
                    xAxis.position = XAxis.XAxisPosition.BOTTOM
                    xAxis.granularity = 1f
                    xAxis.valueFormatter = object : ValueFormatter() {

                        override fun getFormattedValue(value: Float): String {
                            val index = value.toInt()
                            return if (index >= 0 && weekArray.size - 1 >= index) weekArray[index]
                            else ""
                        }
                    }
                    description.isEnabled = false
                    legend.isEnabled = false
                    setPinchZoom(true)
                    renderer = RoundBarChartRender(
                        this,
                        animator,
                        viewPortHandler
                    )
                }
                if (isRefresh) invalidate()
            }
        }

    }

}